/**
 * 获取一个范围内的随机整数
 * @param {number} a 表示范围的数字
 * @param {number} b 表示范围的数字
 */
function getRandom(a,b){
    var max = a;
    var min = b;
    if(a<b){
        max = b
        min = a
    }
    return parseInt(Math.random() * (max-min)) + min
}
/**
 * 获取随机颜色值
 * @param {boolean} hex 是否是16进制的结果
 */
function getColor(hex=true){
    if(!hex){
        return 'rgb('+getRandom(256,0)+','+getRandom(256,0)+','+getRandom(256,0)+')'
    }
    var color = '#'
    for(var i=0;i<3;i++){
        var num2 = getRandom(256,0)
        num2 = num2.toString(16)
        if(num2.length === 1){
            num2 = '0' + num2
        }
        color += num2
    }
    return color;
}
/**
 * 兼容的获取样式的函数
 * @param {node} ele 获取样式的那个标签元素
 * @param {string} attr 获取样式中的css属性名
 */
function getStyle(ele,attr){
    if(window.getComputedStyle){
        return window.getComputedStyle(ele)[attr]
    }else{
        return ele.currentStyle[attr]
    }
}
/**
 * 绑定事件的函数
 * @param {node} ele 要绑定事件的元素
 * @param {string} type 要绑定的事件类型
 * @param {function} fn 要处理事件的函数
 */
function bindEvent(ele,type,fn){
    if(ele.addEventListener){
        ele.addEventListener(type,fn)
    }else{
        ele.attachEvent('on'+type,fn)
    }
}
/**
 * 解绑事件的函数
 * @param {node} ele 要绑定事件的元素
 * @param {string} type 要绑定的事件类型
 * @param {function} fn 要处理事件的函数
 */
function unBind(ele,type,fn){
    if(ele.removeEventListener){
        ele.removeEventListener(type,fn)
    }else{
        ele.detachEvent('on'+type,fn)
    }
}
/**
 * 设置样式的函数
 * @param {node} ele 要设置样式的那个标签对象
 * @param {object} styleObj 要设置的样式，css的属性和值组成的对象
 */
function setStyle(ele,styleObj){
    for(var attr in styleObj){
        ele.style[attr] = styleObj[attr]
    }
}
/**
 * 动画函数
 * @param {node} ele 要运动的元素
 * @param {object} obj 要运动的属性组成的对象
 */
function move(ele,obj,fn=function(){}){
    var k = 0
    var n = 0
    for(let attr in obj){
        k++
        let timerId = setInterval(function(){
            var target = obj[attr]
            var style = getStyle(ele,attr)
            if(attr === 'opacity'){
                style *= 100
                target *= 100
            }
            style = parseInt(style)
            var diff = target - style;
            var speed = diff/20
            if(speed>0){
                speed = Math.ceil(speed)
            }else{
                speed = Math.floor(speed)
            }
            style += speed
            if(style === target){
                style = target
                if(attr === 'opacity'){
                    ele.style[attr] = style/100
                }else{
                    ele.style[attr] = style  +"px"
                }
                clearInterval(timerId)
                n++
                if(n === k){
                    fn()
                }
            }else{
                if(attr === 'opacity'){
                    ele.style[attr] = style/100
                }else{
                    ele.style[attr] = style  +"px"
                }
            }
            
        },20)
    }
}
// 分页插件
// 定义构造函数
function Page(classname,obj={}){
    this.obj = obj
    this.show = obj.show || function(){}
    this.default = {
        pageData:{
            total:100,
            pageSize:12,
        },
        symbol:{
            first:"首页",
            prev:"上一页", 
            list:'',
            next:"下一页", 
            last:"末页" 
        }
    }
    this.setDefault()
    this.totalPage = Math.ceil(this.default.pageData.total / this.default.pageData.pageSize)
    this.currentPage = 1
    this.list = null
    this.box = document.querySelector('.'+classname)
    this.container = document.createElement('div')
    this.setStyle(this.container,{
        width:"100%",
        height:"50px",
        display:"flex",
        justifyContent:"center",
        "align-items":"center"
    })
    this.container.onmouseover = ()=>{
        this.container.style.cursor = "pointer"
    }
    this.container.onselectstart = ()=>{
        return false;
    }
    this.box.appendChild(this.container)
    this.createTag()
    this.init()
    this.skip()
    this.tabPage()
}
Page.prototype.init = function(){
    this.createPage()
    this.setDisabled()
    // this.container.children[5].value = this.currentPage
    this.show(this.currentPage)
}
Page.prototype.skip = function(){
    var input = document.createElement('input')
    input.setAttribute('type','number')
    this.container.appendChild(input)
    this.setStyle(input,{
        outline: 'none',
        padding: '6px',
        border: '1px solid #ccc',
        width: '46px',
        height: '19px',
        margin:"0 5px"
    })
    var btn = document.createElement('button')
    btn.innerText = 'GO';
    this.container.appendChild(btn)
    this.setStyle(btn,{
        width: '46px',
        height: '33px',
        outline: 'none',
        border: '1px solid #ccc',
        margin: '0 5px',
        "background-color": 'skyblue',
    })
    btn.onmouseover = ()=>{
        btn.style.cursor = "pointer"
    }
}
Page.prototype.setDisabled = function(){
    if(this.currentPage === 1){
        this.container.children[0].style.backgroundColor = '#eee';
        this.container.children[1].style.backgroundColor = '#eee';
        this.container.children[0].setAttribute('disabled','true')
        this.container.children[1].setAttribute('disabled','true')
    }else{
        this.container.children[0].style.backgroundColor = 'transparent';
        this.container.children[1].style.backgroundColor = 'transparent';
        this.container.children[0].removeAttribute('disabled')
        this.container.children[1].removeAttribute('disabled')
    }
    if(this.currentPage === this.totalPage){
        this.container.children[3].style.backgroundColor = '#eee';
        this.container.children[4].style.backgroundColor = '#eee';
        this.container.children[3].setAttribute('disabled','true')
        this.container.children[4].setAttribute('disabled','true')
    }else{
        this.container.children[3].style.backgroundColor = 'transparent';
        this.container.children[4].style.backgroundColor = 'transparent';
        this.container.children[3].removeAttribute('disabled')
        this.container.children[4].removeAttribute('disabled')
    }
}
Page.prototype.tabPage = function(){
    this.container.onclick = e=>{
        var e = e || window.event;
        var target = e.target || e.srcElement;
        if(target.className === 'first' && target.getAttribute('disabled')!=='true'){
            this.currentPage = 1
            this.init()
        }else if(target.className === 'prev' && target.getAttribute('disabled')!=='true'){
            this.currentPage--
            this.init()
        }else if(target.className === 'next' && target.getAttribute('disabled')!=='true'){
            this.currentPage++
            this.init()
        }else if(target.className === 'last' && target.getAttribute('disabled')!=='true'){
            this.currentPage = this.totalPage
            this.init()
        }else if(target.tagName === "P" && target.innerText-0 !== this.currentPage){
            this.currentPage = target.innerText-0
            this.init()
        }else if(target.tagName === 'BUTTON' && this.currentPage!==target.previousElementSibling.value-0){
            if(target.previousElementSibling.value-0>=this.totalPage){
                target.previousElementSibling.value = this.totalPage
            }
            if(target.previousElementSibling.value-0<=1){
                target.previousElementSibling.value = 1
            }
            this.init()
        }
    }
}
Page.prototype.createP = function(start,end){
    for(var i=start;i<=end;i++){
        var p = document.createElement('p')
        p.innerText = i;
        this.setStyle(p,{
            margin:"5px",
            padding:"5px",
            border:"1px solid #ccc"
        })
        if(i === this.currentPage){
            p.style.backgroundColor = 'orange';
        }
        this.list.appendChild(p)
    }
}
Page.prototype.createPage = function(){
    this.list.innerHTML = '';
    if(this.totalPage<=5){
        this.createP(1,this.totalPage)
    }else{
        if(this.currentPage<=3){
            this.createP(1,5)
        }
        else if(this.currentPage>=this.totalPage-2){
            this.createP(this.totalPage-4,this.totalPage)
        }
        else{
            this.createP(this.currentPage-2,this.currentPage+2)
        }
    }
}
Page.prototype.setStyle = function(ele,styleObj){
    for(var attr in styleObj){
        ele.style[attr] = styleObj[attr]
    }
}
Page.prototype.createTag = function(){
    for(var attr in this.default.symbol){
        var div = document.createElement('div')
        div.innerText = this.default.symbol[attr]
        if(attr !== 'list'){
            this.setStyle(div,{
                margin:"5px",
                padding:"5px",
                border:"1px solid #ccc"
            })
        }else{
            this.list = div
            this.setStyle(div,{
                display:"flex",
                justifyContent:"center",
                alignItems:"center"
            })
        }
        div.className = attr
        this.container.appendChild(div)
    }
}
Page.prototype.setDefault = function(){
    for(var attr in this.obj.pageData){
        this.default.pageData[attr] = this.obj.pageData[attr]
    }
    for(var attr in this.obj.symbol){
        this.default.symbol[attr] = this.obj.symbol[attr]
    }
}
// 分页插件使用示例
// 参数1：要放分页的大盒子的类名
// 参数2：插件的配置
// pageData代表分页数据 - 需要total键和pageSize键，分别代表总共多少条数据，每页显示多少条
// new Page('pagination',{
//     pageData:{
//         total:arr.length,
//         pageSize
//     },
//     // symbol表示显示的符号
//     symbol:{
//         first:'',
//         prev:'',
//         next:'',
//         last:''
//     },
//     // 使用插件，需要有真实的数据，截取数据使用
//     show:function(currentPage){
//         var brr = arr.slice((currentPage-1)*pageSize,currentPage*pageSize)
//         var str = '';
//         for(var i=0;i<brr.length;i++){
//             str += `
//                 <tr>
//                     <td>${brr[i].id}</td>
//                     <td>${brr[i].name}</td>
//                     <td>${brr[i].sex}</td>
//                     <td>${brr[i].age}</td>
//                 </tr>
//             `
//         }
//         document.querySelector('tbody').innerHTML = str
//     }
// })

/**
 * 设置cookie的函数
 * @param {string} key 设置的cookie的键
 * @param {string} value cookie的值
 * @param {number} seconds 秒数
 * @param {string} path 路径
 */
function setCookie(key,value,seconds,path='/'){
	var date = new Date()
	date.setTime(date.getTime()-8*3600*1000+seconds*1000)
	document.cookie = `${key}=${value};expires=${date};path=${path}`
}
/**
 * 获取cookie的函数
 * @param {string} key 要获取的cookie的键
 */
function getCookie(key){
	var cookies = document.cookie;
	var arr = cookies.split('; ')
	for(var i=0;i<arr.length;i++){
		var brr = arr[i].split('=')
		if(brr[0] === key){
			return brr[1]
		}		
	}	
}
/**
 * 删除cookie的函数
 * @param {string} key cookie的键
 * @param {string} path 路径
 */
function removeCookie(key,path='/'){
	setCookie(key,null,-1,path)
}